'''
Descripttion: 
version: 
Author: lihk
Date: 2023-09-20 10:53:49
LastEditors: lihk
LastEditTime: 2023-09-20 11:13:53
'''
import os
from pymodule import zipFileModule
from pymodule import sshModule


class BuildProject:
    def build(self, cmd):
        # 设置编码
        print('------start build-------', cmd)

        # 获取当前工作目录
        work_path = os.getcwd()

        # 切换工作目录
        try:
            os.chdir(work_path)
        except FileNotFoundError:
            print(f'{work_path} not found')
            return

        # 执行打包命令
        result = os.system(cmd)

        if result == 0:
            print('build success')
        else:
            print(f'error: {result}')


if __name__ == "__main__":
    buildDisct = {
        "cmdList": ["npm run build", "npm run build:test"],# 前端多环境打包命令
        "zipFileName": ["dist", "dist2"],# 生成的打包路径进行文件压缩
        "ssh": [
            {"host": 'xx.xx.xx.xxx',#服务器ip
              "port": 22,# 端口号
             "user": 'root', # 账号
             "private_key_path": 'E:\XXXX',# 本地的密钥路径
             "remote_directory": './nginx/html/web2',# 上传服务器路径
             "local_zip_path": r'E:\xx\dist\dist.zip',# 上传本地路径前端打包的zip
             "out_dir": 'dist'# 上传服务器指定的文件
             },
             {"host": 'xx.xx.xx.xxx',#服务器ip
              "port": 22,# 端口号
             "user": 'root', # 账号
             "private_key_path": 'E:\XXXX',# 本地的密钥路径
             "remote_directory": './nginx/html/web2',# 上传服务器路径
             "local_zip_path": r'E:\xx\dist2\dist2.zip',# 上传本地路径前端打包的zip
             "out_dir": 'dist'# 上传服务器指定的文件
             },
        ]
    }

    # 有效的构建模式选项列表
    valid_modes = ['all', 'formal', 'test']

    # 获取用户输入,直到输入正确才执行，输入错误就继续让输入
    while True:
        # 获取用户输入
        choice = input("Select build mode (all/formal/test): ")
        # 验证用户输入是否有效
        if choice in valid_modes:
            # 输入正确，跳出循环
            break
        else:
            print("Please enter a valid build mode")

    def perform_build_and_zip(cmd, out_dir, i):
        project = BuildProject()
        print(cmd)
        project.build(cmd)
        # 压缩成zip包
        zipFileModule.zip_directory_contents(out_dir, f'{out_dir}.zip')
        sshModule.upload_file(buildDisct["ssh"][i])

    if choice == 'all':
        for i, cmd in enumerate(buildDisct['cmdList']):
            perform_build_and_zip(cmd, buildDisct["zipFileName"][i], i)
    elif choice == 'formal':
        perform_build_and_zip(
            buildDisct['cmdList'][0], buildDisct["zipFileName"][0], 0)
    elif choice == 'test':
        perform_build_and_zip(
            buildDisct['cmdList'][1], buildDisct["zipFileName"][1], 1)
